package com.fantasy.service;

import java.util.ArrayList;

import com.fantasy.EventListener;
import com.fantasy.TaskController;
import com.fantasy.User;
import com.fantasy.WimNotificationManager;
import com.fantasy.ui.MessageBoxActivity;
import com.fantasy.util.IMUtil;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

public class WimService extends Service {

	private static final boolean DEBUG = true;
	private static final String TAG = "WimService";

	private static final int MESSAGE_NEW_USER = 0;
	private static final int MESSAGE_REMOVE_USER = 1;
	private static final int MESSAGE_INCOMING_MSG = 2;

	static final int MSG_REGISTER_CLIENT = 2;
	static final int MSG_UNREGISTER_CLIENT = 2;

	final RemoteCallbackList<IRemoteServiceCallback> mCallbacks = new RemoteCallbackList<IRemoteServiceCallback>();
	ArrayList<Messenger> mClients = new ArrayList<Messenger>();
	WimNotificationManager mWm;

	private TaskController mTc;
	private StringBuilder mIpBuilder = new StringBuilder();

	private String mIp = null;
	private String mContent = null;
	private SocketEventListener mSocketListener = new SocketEventListener();

	@Override
	public IBinder onBind(Intent intent) {
		if (DEBUG) {
			Log.d(TAG, "onBind:");
		}
		if (IRemoteService.class.getName().equals(intent.getAction())) {
			return mBinder;
		}
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		if (DEBUG) {
			Log.d(TAG, "onCreate");
		}
		mWm = new WimNotificationManager(this);
		mWm.showRunningNotification();
		mTc = TaskController.getInstance();
		mTc.registerObserver(mSocketListener);

	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if (DEBUG) {
			Log.d(TAG, "start WimService");
		}
	}
	/**
	 * The IRemoteInterface is defined through IDL
	 * 
	 */
	private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {

		public void unregisterCallback(IRemoteServiceCallback cb)
				throws RemoteException {
			if (cb != null)
				mCallbacks.unregister(cb);
		}

		public void registerCallback(IRemoteServiceCallback cb)
				throws RemoteException {

			if (cb != null) {
				mCallbacks.register(cb);
				if (DEBUG) {
					Log.d(TAG, "register:");
				}
			}
		}

		public void quit() throws RemoteException {
			if (mTc != null) {
				mTc.stopAllThread();
			}
		}

		public void sendDirectry() throws RemoteException {

		}

		public void sendFile() throws RemoteException {

		}
		public void startLogin() throws RemoteException {
			if (mTc != null) {
				mTc.mTaskType = TaskController.TASK_LOGIN;
				mTc.startTask(WimService.this);
			}
		}

		public String getIpList() throws RemoteException {
			if (mTc != null) {
				if (DEBUG) {
					Log.d(TAG, "getIpList:" + mIpBuilder.toString());
				}
				return mIpBuilder.toString();
			}
			return null;
		}

		public void sendMessage(String message) throws RemoteException {
			mTc.mTaskType = TaskController.TASK_SEND_MESSAGE;
			//mTc.mTargetAddress = mIp;
			mTc.mMsgContent = message;
			mTc.startTask(WimService.this);
		}

	};

	@Override
	public void onDestroy() {
		if (DEBUG) {
			Log.d(TAG, "onDestroy");
		}
		mWm.cancelRunningNotification();
		mCallbacks.kill();
		mTc.stopAllThread();
	}

	private class SocketEventListener extends EventListener {
		@Override
		public void addUser(String ip) {
			super.addUser(ip);
			if (DEBUG) {
				Log.d(TAG, "addUser:" + ip);
			}
			mIpBuilder.append(ip);
			mIpBuilder.append(IMUtil.SPLIT);
			Message msg = new Message();
			msg.arg1 = MESSAGE_NEW_USER;
			msg.obj = ip;
			mHandler.sendMessage(msg);

		}

		@Override
		public void newMessage(String message) {
			super.newMessage(message);
			Message msg = new Message();
			msg.arg1 = MESSAGE_INCOMING_MSG;
			msg.obj = message;
			mHandler.sendMessage(msg);
		}

		@Override
		public void onEvent(ArrayList<User> al) {
			super.onEvent(al);
		}

		@Override
		public void removeUser(String ip) {
			super.removeUser(ip);
			Message msg = new Message();
			msg.arg1 = MESSAGE_REMOVE_USER;
			msg.obj = ip.toString();
			int startIndex = mIpBuilder.indexOf(ip);
			int length = ip.length();
			Log.d(TAG, "removeUser:IPBuilder:" + mIpBuilder.toString());
			//mIpBuilder.delete(startIndex, startIndex + length + 1);
			Log.d(TAG, "removeUser:IPBuilder:" + mIpBuilder.toString());
			//mHandler.sendMessage(msg);
		}

	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.arg1) {
			case MESSAGE_NEW_USER:

				final int N = mCallbacks.beginBroadcast();
				if (DEBUG) {
					Log.d(TAG, "handleMessage:N" + N);
				}
				for (int i = 0; i < N; i++) {
					try {
						mCallbacks.getBroadcastItem(i).addUser(
								msg.obj.toString());
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
				mCallbacks.finishBroadcast();
				break;
			case MESSAGE_REMOVE_USER:
				final int R = mCallbacks.beginBroadcast();
				for (int i = 0; i < R; i++) {
					try {
						mCallbacks.getBroadcastItem(i).rmUser(
								msg.obj.toString());
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
				mCallbacks.finishBroadcast();
				break;
			case MESSAGE_INCOMING_MSG:
				mWm.showNotification(msg.obj.toString());

				Intent intent = new Intent();
				parseMsg(msg.obj.toString());
				if (mIp != null) {
					intent.putExtra(MessageBoxActivity.MESSAGE_IP, mIp);
				}
				if (mContent != null) {
					intent.putExtra(MessageBoxActivity.MSG_CONTENT, mContent);
				}
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setAction("com.fantasy.newmessage");
				startActivity(intent);
				break;
			}

		}

	};

	// MESSAGE format:MESSAGE:192.168.1.111:myself:你好,ddfd:
	private void parseMsg(String message) {
		if (DEBUG) {
			Log.d(TAG,"parseMsg:"+message);
		}
		String args[] = message.split(IMUtil.SPLIT);
		mIp = args[2];
		mContent = args[3];
	}
}
